from bitstring import BitStream

import BodyMessages as msgs


def build(msg_id):
    global message_obj

    parser = {
        '0001': msgs.CommonResponse,
        '8001': msgs.CommonResponse,
        '0002': msgs.KeepAlive,
        '0100': msgs.TerminalRegistry,
        '0200': msgs.PositionInfoReport,
        '0800': msgs.MediaEventUpload,
        # '0801': msgs.MediaDataUpload,
        '8103': msgs.SetTerminalParameter,
        '8800': msgs.MediaDataUploadResponse,
        '8801': msgs.TakePhoto,
        '8802': msgs.MediaDataRetrieval,
        '0803': msgs.MediaDataRetrievalResponse,
        '0801': msgs.MediaDataUploadRequest,
        '0901': msgs.DataCompressReport,
        '8a00': msgs.RSAPublicKey,
        '0a00': msgs.RSAPublicKey,
        '1003': msgs.AudioVideoAttributeUpload,
        '9101': msgs.RealTimeAudioVideoTransferRequest,
        '9102': msgs.RealTimeAudioVideoTransferControl,
        '9105': msgs.RealTimeAudioAudioTransferStatusNotify,
        '9205': msgs.QueryResourcesList,
        '1205': msgs.ResourcesListUpload,
        '9201': msgs.RemoteVideoPlaybackRequest,
        '9202': msgs.RemoteVideoPlaybackControl,
        '9206': msgs.FileUploadRequest,
        '1206': msgs.FileUploadComplete,
        '9207': msgs.FileUploadControl,
    }

    if "message_obj" not in globals():
        message_obj = {}
    if msg_id not in message_obj:
        message = parser.get(msg_id)
        if message:
            message = message()
            message_obj[msg_id] = message
        else:
            raise ValueError("Message not found")

    return message_obj[msg_id]


def parse(body: BitStream, msg_id: str):
    message = build(msg_id)
    return message.parse(body)
